package app

import (
	"errors"
	"gitee.com/cristiane/web_gin_template/vars"
	"gitee.com/kelvins-io/common/json"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"strings"
)

func BindAndValid(c *gin.Context, form interface{}) error {
	if err := c.Bind(form); err != nil {
		return err
	}
	go recordLog(c, form)
	valid := validation.Validation{}
	check, err := valid.Valid(form)
	if err != nil {
		return err
	}
	if !check {
		err := buildFormErr(valid.Errors)
		go markErrors(c, form, err)
		return err
	}
	return nil
}

func buildFormErr(errs []*validation.Error) error {
	var msg strings.Builder
	for _, v := range errs {
		msg.WriteString(v.Field)
		msg.WriteString("：")
		msg.WriteString(v.Error())
		msg.WriteString("；")
	}
	return errors.New(msg.String())
}

func recordLog(ctx *gin.Context, form interface{}) {
	vars.AccessLogger.Infof(ctx, "ip: %v, form: %v", ctx.ClientIP(), json.MarshalToStringNoError(form))
}

func markErrors(ctx *gin.Context, form interface{}, err error) {
	vars.AccessLogger.Infof(ctx, "ip: %v, params err: %v,err: %v", ctx.ClientIP(), json.MarshalToStringNoError(form), err.Error())
	return
}
